//
//  WmcHomeVC+ViewAction.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/7/21.
//

import UIKit
import YPGraphicEngine

extension WmcHomeVC {
    /// 视图事件
    func viewActionBind() {
        navgationAction()
        centerViewAction()
        footerViewAction()
        bottomViewAction()
    }

    fileprivate func navgationAction() {
        // 返回（其他平台会有）
        headerView.backControl.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.backAction()
        }

        // 点击设置的菜单
        headerView.menuBtn.yp.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.showSettingVC()
        }
        // 画幅调整
        headerView.aspectRatioBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.headerView.aspectRatioBtn.aspectRatio = btn.aspectRatio
            YPDevice.PlayShake(.heavy)
            weakSelf.setAspectRatio(btn.aspectRatio)
            weakSelf.autoFrame()
            weakSelf.viewModel.photoAspectRatio = btn.aspectRatio // 记录拍照模式下使用的画幅比
            WmcUserdefault.save(value: btn.aspectRatio.rawValue, forKey: .State.Camera.aspectRatio)
        }


        // 画幅调整
        aspectRatioView.didSelectedRatio.subscribe(onNext: {
            [weak self] ratio in
            guard let self = self else { return }
            self.headerView.aspectRatioBtn.aspectRatio = ratio
            YPDevice.PlayShake(.heavy)
            self.setAspectRatio(ratio)
            self.autoFrame()
            self.viewModel.photoAspectRatio = ratio // 记录拍照模式下使用的画幅比
            WmcUserdefault.save(value: ratio.rawValue, forKey: .State.Camera.aspectRatio)
        }).disposed(by: rx.disposeBag)
        

        // 点击翻转
        headerView.flipBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.clickFlip()
        }

        // 点击邀请好友
        headerView.invitationBtn.yp.addEvent { btn in
            WmcNavigatorManager.push(.invitation)
        }

        // 点击闪光灯
        headerView.flashBtn.actionBlock = { [weak self] btn in
            guard let self = self else { return }
            if case .video = self.viewModel.functionMode {
                let flashMode: YPGECamera.FlashMode = (btn.flashMode == .off ? .torch : .off)
                self.setFlashMode(flashMode, cacheState: true)
            } else {
                self.setFlashSelectView(shown: true, mode: btn.flashMode)
            }
        }
        
        // 闪光灯模式改变
        flashSelectView.didSelectedFlashMode.subscribe(onNext: {
            [weak self] mode in
            guard let self = self else { return }
            self.setFlashSelectView(shown: false)
            self.setFlashMode(mode, cacheState: true)
        }).disposed(by: rx.disposeBag)

        // 点击意见反馈
        headerView.feedBackBtn.yp.addEvent { [weak self] _ in
            // 调用优化之后的h5页面
            guard let weakSelf = self else { return }
            weakSelf.stopCamera()
            let vm = WmcHtml5VM()
            vm.parameters = nil
            vm.questionType = .None
            vm.path = WmcHtml5VM.Html5Path.feedback
            WmcNavigatorManager.push(.html5Page, parms: vm)
        }
        // 点击滤镜
        headerView.filterBtn.yp.addEvent {
            [weak self] _ in
            guard let self = self else { return }
            self.setFilterView(shown: true)
        }
        // 延时拍照
        headerView.delayBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.headerView.delayBtn.delayTime = btn.delayTime
        }
        // 点击滤镜View的关闭按钮
        filterView.closeAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.setFilterView(shown: false)
        }).disposed(by: rx.disposeBag)
        // 点击滤镜View的对比按钮
        filterView.contrastAction.subscribe(onNext: {
            [weak self] event in
            guard let self = self else { return }
            switch event {
            case .down: // 按下
                self.cameraView?.removeAllFilter()
            case .up: // 抬起
                self.addFilter()
            }
        }).disposed(by: rx.disposeBag)
        // 选中某个滤镜效果
        filterView.didSelecteFilterItem.subscribe(onNext: {
            [weak self] filterItem in
            guard let self = self else { return }
            // 更新滤镜数据源,刷新页面
            self.viewModel.didSelected(filterItem: filterItem)
            self.filterView.reloadData()
            // 添加滤镜
            self.addFilter()
            // 存储滤镜的名字
            WmcUserdefault.save(value: filterItem.name, forKey: .State.Camera.filter)
        }).disposed(by: rx.disposeBag)
        
        // 点击二维码图片
        staticQRView.rx.tapGesture().when(.recognized).subscribe(onNext: {
            [weak self] _ in
            guard let self = self else { return }
            self.showSettingVC()
        }).disposed(by: rx.disposeBag)
        
        // 点击二维码用户引导的确定按钮
        qrVerifyGuideView.okButtonAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.qrVerifyGuideView.isHidden = true
            self.qrVerifyGuideView.removeFromSuperview()
            WmcUserdefault.save(value: true, forKey: .Tips.Home.hasShownQrVerifyGuide)
            // 将二维码置于定位按钮下面
            self.view.insertSubview(self.staticQRView, belowSubview: self.positioningBtn)
        }).disposed(by: rx.disposeBag)
        // 点击拼图引导
        combineGuideView.okButtonAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.combineGuideView.isHidden = true
            self.combineGuideView.removeFromSuperview()
        }).disposed(by: rx.disposeBag)
        
        // 点击排版按钮
        layoutButton.yp.addEvent {
            [weak self] action in
            guard let self = self else { return }
            self.showPhotoLayoutAlert()
        }
        // 选择焦距倍数
        focusAdjustView.didSelectedFocusScale.subscribe(onNext: {
            [weak self] scale in
            guard let self = self else { return }
            self.controlView.setCameraZoomFactor(scale: scale)
        }).disposed(by: rx.disposeBag)
        // 将要缩放改变焦距
        controlView.willChangeFocus.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.focusAdjustView.showRuleView()
        }).disposed(by: rx.disposeBag)
        
        // 焦距倍数变化
        controlView.focusZoomScaleChanged.subscribe(onNext: {
            [weak self] scale in
            guard let self = self else { return }
            self.focusAdjustView.set(scale: scale, isShowScales: true)
        }).disposed(by: rx.disposeBag)
        
        // 已经结束缩放改变焦距
        controlView.didEndChangeFocus.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.focusAdjustView.hideRuleView(delay: true)
        }).disposed(by: rx.disposeBag)
        
        // 通知视图开始布局时，控制视图需要忽略的区域
        noticeView.noticeLayoutBlock = { [weak self] hitViews in
            guard let weakSelf = self else { return }
            weakSelf.controlView.ignoreViews2 = hitViews
        }
    }

    fileprivate func centerViewAction() {

        // 水印被点击时候
        watermarkContentView.watermarkActionBlock = { [weak self] view in
            guard let weakSelf = self,
                  let watermarkModel = weakSelf.watermarkContentView.watermarkModel else { return }
            weakSelf.editWatermark(watermarkModel)
        }

        // 水印开始布局时，控制视图需要忽略的区域
        watermarkContentView.watermarkLayoutBlock = { [weak self] hitViews in
            guard let weakSelf = self else { return }
            weakSelf.controlView.ignoreViews = hitViews
            weakSelf.noticeView.ignoreViews = hitViews
            if let wmView = weakSelf.watermarkContentView.watermarkView {
                weakSelf.controlView.updateDottedLayer(watermarkView: wmView)
            }
            // 调用代理
            if let homeDelegate = weakSelf.homeDelegate,
               let watermarkView = weakSelf.watermarkContentView.watermarkView,
               let watermarkModel = weakSelf.watermarkContentView.watermarkModel
            {
                homeDelegate.watermarkViewLayoutComplete(.current,
                                                         watermarkView: watermarkView,
                                                         watermarkModel: watermarkModel)
            }
        }

        watermarkContentView.isWatermarkMoveBlock = { [weak self] in
            guard let weakSelf = self else { return true }
            if let watermarkModel = weakSelf.watermarkContentView.watermarkModel,
               let isAllow = weakSelf.homeDelegate?.watermarkViewIsAllowMove(.current,
                                                                             watermarkModel: watermarkModel)
            {
                return isAllow
            }
            return true
        }

        // 水印开始移动时，控制视图需要处理什么
        watermarkContentView.watermarkMoveBlock = { [weak self] watermarkView in
            guard let weakSelf = self else { return }
            weakSelf.controlView.watermarkMove(watermarkView)
            // 调用代理
            if let homeDelegate = weakSelf.homeDelegate,
               let watermarkView = weakSelf.watermarkContentView.watermarkView,
               let watermarkModel = weakSelf.watermarkContentView.watermarkModel
            {
                homeDelegate.watermarkViewMove(.current,
                                               watermarkView: watermarkView,
                                               watermarkModel: watermarkModel)
            }
        }
        // 控制视图被操作时
        controlView.hitTestBlock = { [weak self] in
            guard let self = self else { return }
            self.locationGuideView.isHidden = true
            // 隐藏画幅选择
            self.setAspectRatioView(shown: false)
            // 隐藏滤镜view
            self.setFilterView(shown: false)
            // 隐藏闪光灯选择
            self.setFlashSelectView(shown: false)
        }

//        locationTipView.clickClosure = {
//            [weak self] type in
//            guard let self = self else { return }
//            self.locationTipView.dismiss()
//            let locationStatus = WmcAuthorizedManager.location()
//            if locationStatus == .notDetermined {
//                WmcAuthorizedManager.locationRequest { [weak self] status in
//                    guard let weakSelf = self else { return }
//                    if status.info.isAvailable { // 有权限
//                        WmcLocationManager.startLocation() // 开始定位
//                        weakSelf.viewModel.locationTipsDismiss.accept(())
//                    } else {
//                        weakSelf.viewModel.locationNotAuthorized?() // 未获取权限回调
//                    }
//                }
//            } else {
//                guard let url = URL(string: UIApplication.openSettingsURLString) else {
//                    return
//                }
//                if #available(iOS 10.0, *) {
//                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
//                } else {
//                    UIApplication.shared.openURL(url)
//                }
//            }
//
//        }

        networkErrorTipView.clickClosure = { [weak self] type in
            guard let weakSelf = self else { return }
            let networkType = YPNetworkReachability.queryNetworkReachabilityType()
            if networkType == .cellular || networkType == .ethernetOrWiFi {
                WmcLocationManager.stopLocation()
                WmcLocationManager.startLocation()
                weakSelf.networkErrorTipView.dismiss()
            } else {
                WmcHudManager.toast("请检查网络连接后重试")
            }
        }

        // 点击重新定位
        positioningBtn.yp.addEvent { btn in
            let vm = WmcSelectAddressVM()
            vm.isShowSetCommonAddress = true
            WmcNavigatorManager.push(.selectAddress, parms: vm)
        }
    }
    
    /// 监听相机摄像头切换
    func listenCameraRotate() {
        // 摄像头即将切换
        cameraView?.setWillRotateCameraBlock {
            [weak self] position in
            guard let weakSelf = self else { return }
            weakSelf.headerView.refreshFlashBtnState(weakSelf.cameraView)
            if position == .front { // 如果切换至前置摄像头
                // 先设置闪光灯
                weakSelf.setFlashMode(.off, cacheState: false)
                // 修改分辨率(切换前置摄像头时,要在切换前调整分辨率)
                weakSelf.setCameraPreset(position: position)
            }
            
        }
        // 已经切换完成
        cameraView?.setDidRotateCameraBlock {
            [weak self] position in
            guard let weakSelf = self else { return }
            weakSelf.headerView.refreshFlashBtnState(weakSelf.cameraView)
            if position == .back {
                // 修改分辨率(切换后置摄像头时,要在切换后调整分辨率)
                weakSelf.setCameraPreset(position: position)
            }
        }
    }

    func showWatermarkAlertView() {
        // 隐藏相机上水印
        watermarkContentView.isHidden = true
        controlView.isHidden = true
        // 加载水印
        watermarkSelectView.show(selectWatermark: watermarkContentView.watermarkModel)
    }
    
    
    func showObjectRecognitionAlertView() {
        
        let view = WmcRecognitionView.show()

        view.selectedItem = { [weak self] model in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.recognitionModel = model
            weakSelf.controlView.aiLogoView.updateModel(model)
        }

        let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: view, contentLayoutBlock: { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(413)
        }))
        presentVC.show()
    }

    fileprivate func footerViewAction() {
        // 点击水印选择按钮
        footerView.watermarkBtn.yp.addEvent { [weak self] _ in
            guard let weakSelf = self else { return }
            weakSelf.showWatermarkAlertView()
            // 记录红点
            WmcUserdefault.save(value: true, forKey: .Tips.Home.watermarkSelectBtnPoint)
            weakSelf.footerView.watermarkRedPoint.isHidden = true
        }

        // ---水印选择
        watermarkSelectView.didSelectWatermarkBlock = { [weak self] _, wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setWatermarkModel(wmModel)
        }

        // ---无水印选择
        watermarkSelectView.didSelectEmptyWatermarkBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.viewModel.setWatermarkModel(wmModel)
        }

        // ---水印编辑
        watermarkSelectView.editWatermarkBlock = { [weak self] wmModel in
            guard let weakSelf = self else { return }
            weakSelf.editWatermark(wmModel)
        }
        // ---水印分享
        watermarkSelectView.shareWatermarkBlock = { wmModel in
            let vm = WmcShareWatermarkVM()
            vm.watermarkModel = wmModel
            WmcNavigatorManager.push(.shareWatermark, parms: vm)
        }
        // ---水印选择即将消失
        watermarkSelectView.willDismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 显示相机上水印
            weakSelf.watermarkContentView.isHidden = false
            weakSelf.controlView.isHidden = false
        }

        // ---水印选择需要消失
        watermarkSelectView.dismissBlock = { [weak self] in
            guard let weakSelf = self else { return }
            // 显示相机上水印
            weakSelf.watermarkContentView.isHidden = false
            weakSelf.controlView.isHidden = false
        }

        // 水印加载完成
        watermarkSelectView.watermarkListLoadCompletion = { [weak self] list in
            guard let weakSelf = self else { return }
            weakSelf.homeDelegate?.watermarkListDidLoad(.current, list: list)
        }

        // 底部视图被操作时
        footerView.hitTestBlock = { [weak self] in
            guard let self = self else { return }
            self.locationGuideView.isHidden = true
            // 隐藏画幅选择
            self.setAspectRatioView(shown: false)
            // 隐藏滤镜view
            self.setFilterView(shown: false)
            // 隐藏闪光灯选择
            self.setFlashSelectView(shown: false)
        }

        // 点击本地相册
        footerView.localAlbumBtn.yp.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.clickLocalAlbumBtn()
        }

        footerView.objectRecognitionBtn.yp.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.showObjectRecognitionAlertView()
        }

        // 点击云相册
        footerView.cloudAlbumBtn.clickClouser = { [weak self] in
            guard let weakSelf = self else { return }
//            weakSelf.stopCamera()
            WmcNavigatorManager.push(.myTeam)
        }

        // 点击拍照
        footerView.actionBtn.yp.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.clickTakePhoto()
        }

        // 点击录制/停止按钮
        footerView.videoActionBtn.yp.addEvent { [weak self] btn in
            let cameraStatus = WmcAuthorizedManager.camera()
            let microphoneStatus = WmcAuthorizedManager.microphone()
            let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
            guard let weakSelf = self else { return }
            if cameraStatus.info.isAvailable { // 有权限
                if microphoneStatus.info.isAvailable { // 有权限
                    if photoAlbumStatus.info.isAvailable || weakSelf.viewModel.hasAlbumAuthorizationAlertForTakePhotoShown { // 有权限或者没有权限但是已提示过权限弹窗
                        btn.isUserInteractionEnabled = false
                        YPDevice.PlayShake(.threeDimensionalTouch_pop)
                        switch weakSelf.viewModel.videoRecordState {
                        case .stop: // 当处于停止状态下，点击按钮，则开始录制
                            weakSelf.startRecording()
                        case .pause: // 当处于暂停状态下，点击按钮，则继续录制
                            weakSelf.stopRecording(breakOffType: .none)
                        case .being: // 当处于进行中时，点击按钮，则停止录制
                            weakSelf.stopRecording(breakOffType: .none)
                        }

                        btn.yp.delayLast(1) { [weak btn] in
                            guard let weakBtn = btn else { return }
                            weakBtn.isUserInteractionEnabled = true
                        }
                    } else { // 无权限并且还没提示过弹窗
                        WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
                        weakSelf.viewModel.hasAlbumAuthorizationAlertForTakePhotoShown = true
                    }
                } else {
                    if microphoneStatus == .notDetermined { // 尚未选择
                        WmcAuthorizedManager.microphoneRequest()
                    } else {
                        WmcAuthorizedManager.showPrivacyAlert(type: .microphone, msg: "授权麦克风权限，才能在视频录制时录制音频")
                    }
                }
            } else {
                WmcAuthorizedManager.showCameraPermissionAlert()
            }
        }

        // 点击暂停/继续录制按钮
        footerView.pauseVideoRecordBtn.actionBlock = { [weak self] btn in
            guard let weakSelf = self else { return }
            YPDevice.PlayShake(.medium)
            switch btn.recordState {
            case .pause: // 点下暂停
                weakSelf.pauseRecording()
            case .continue: // 点下继续
                weakSelf.continueRecording()
            }
        }

        // 点击翻转
        footerView.flipBtn.yp.addEvent { [weak self] btn in
            guard let weakSelf = self else { return }
            weakSelf.clickFlip()
        }

        // 点击滤镜
        footerView.filterBtn.yp.addEvent { _ in
            let filterSelectView = WmcHomeFilterSelectView()
            filterSelectView.show()
        }
        // 拼图(点击完成)
        footerView.combinePhotoAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            // 开始拼图
            self.startCombinePhotos()
        }).disposed(by: rx.disposeBag)
        
        // 取消拼图
        footerView.cancelCombinePhoto.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.showCancelCombinePhotoAlert()
        }).disposed(by: rx.disposeBag)
        
        // 点击撤销
        footerView.undoBtn.yp.addEvent {
            [weak self] _ in
            guard let self = self else { return }
            self.showUndoAlert()
            // 结束引导
            self.finishCombinePhotoGuide()
        }

        // 同步设置弹窗
        let teamBgViewTap = UITapGestureRecognizer()
        footerView.teamBgView.addGestureRecognizer(teamBgViewTap)

        let syncAlert: () -> Void = { [weak self] in
            guard let weakSelf = self else { return }

            let syncSettingsView = WmcSyncSettingsView.showInView(style: .defaultType)
            weakSelf.addSubview(syncSettingsView)

            syncSettingsView.syncTeamCountClosure = { [weak self] count in
                guard let weakSelf = self else { return }
                weakSelf.footerView.updateSyncTeamStatus(count: count)
                weakSelf.footerView.updateCloudAlbumBtnStatus()
            }

            let presentVC = WmcPresentVC(config: .init(style: .sheet(), contentView: syncSettingsView, contentLayoutBlock: { make in
                make.left.right.bottom.equalToSuperview()
                make.height.equalTo(373)
            }))
            presentVC.show()
        }

        teamBgViewTap.rx.event.subscribe { _ in
            WmcLoginManager.checkLogin {
                syncAlert()
            }
        }.disposed(by: rx.disposeBag)
    }

    fileprivate func bottomViewAction() {
        // 点击编辑
        functionSelectView.clickEditBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.edit)
        }

        // 点击数钢筋
        functionSelectView.clickRebarCountBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.rebarCount)
        }

        // 点击照片
        functionSelectView.clickPhotoBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.photo)
        }

        // 点击视频
        functionSelectView.clickVideoBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.video)
        }
        
        // 点击边拍边拼
        functionSelectView.clickPhotoAndCombineBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.switchFunctionMode(.photoAndCombine)
        }


        // 选中功能列表中第一个可选的
        functionSelectView.selectFirstAction()
    }
    
    /// 切换相机模式
    func switchFunctionMode(_ functionModel: WmcButtonItemType.HomeFunctionMode) {
        // 记录功能模式
        if case .edit = functionModel {
        } else {
            viewModel.functionMode = functionModel
        }
        // 更新二维码显示隐藏
        updateQRCodeViewHidden()
        // 二维码引导显示隐藏
        updateQRGuideViewHidden()
        // 引导弹窗
        let guideFinished = viewModel.hasCombinePhotoGuideFinished
        if !guideFinished && viewModel.hasCombinePhotoGuided {
            // 结束引导
            finishCombinePhotoGuide()
        }
        // 排版按钮显示隐藏(注意这里只能用viewModel.functionMode判断,不能用functionModel)
        if case .photoAndCombine = viewModel.functionMode { // 边拍边拼
            layoutButton.isHidden = false
            photoLayoutView.isHidden = false
            let _guideFinished = viewModel.hasCombinePhotoGuideFinished
            if !_guideFinished {
                // 弹出引导弹窗
                showPhotoCombineAlert()
                // 更新引导状态
                footerView.cpGuideState = .stepOne
                // 记录引导状态
                viewModel.hasCombinePhotoGuided = true
            }
        } else {
            layoutButton.isHidden = true
            photoLayoutView.isHidden = true
        }
        // 更新相机分辨率
        setCameraPreset()
        // 重置焦距
        resetCameraFocusScale()
        focusAdjustView.hideRuleView()
        // 设置闪光灯模式
        restoreFlashMode()
        // 切换模式
        switch functionModel {
        case .edit:
            let photoAlbumStatus = WmcAuthorizedManager.photoAlbum()
            if photoAlbumStatus.info.isAvailable {
                // 需要关相机
                stopCamera()
                WmcNavigatorManager.push(.systemAlbum, style: .bottom)
            } else {
                WmcAuthorizedManager.handleAlbumAuthorizationNotAvailable()
            }
        case .rebarCount:
            rebarCountMode()
        case .photo:
            photoMode()
            // 要切换回拍照的画幅比
            setAspectRatio(viewModel.photoAspectRatio, animated: true)
            autoFrame()
        case .video:
            videoMode()
        case .photoAndCombine:
            photoCombineMode()
            // 切换为4:3画幅比
            setAspectRatio(.ar_4_3, animated: true)
            autoFrame()
        default:
            break
        }
    }
    
    /// 弹出设置页面
    private func showSettingVC() {
        let vc = WmcCameraSettingVC()
        // 拍照延时
        vc.delayTime = viewModel.delayTime
        // 画幅比例
        vc.aspectRatio = viewModel.currentAspectRatio
        // 功能模式
        vc.functionMode = viewModel.functionMode
        // 视频清晰度
        vc.articulation = viewModel.articulation
        
        vc.lifeCycleCalled = true
        vc.headerAction.subscribe(onNext: {
            [weak self] action in
            guard let self = self else { return }
            switch action {
            case let .delay(time): // 延时拍照
                self.headerView.delayBtn.delayTime = time
                self.viewModel.delayTime = time
            case .resolution: // 分辨率
                // 跳转分辨率页面
                self.pushResolutionVC()
            case .articulation(let value):
                self.didSwitched(articulation: value)
            case .aspect: // 拍照画幅
                self.setAspectRatioView(shown: true)
            default:
                break
            }
        }).disposed(by: rx.disposeBag)
        vc.switchChanged.subscribe(onNext: {
            [weak self] (type, isOn) in
            guard let self = self else { return }
            switch type {
            case .qrcodeVerify: // 二维码验证开关
                self.updateQRCodeViewHidden()
            default: break
            }
        }).disposed(by: rx.disposeBag)
        vc.show(in: self)
    }
    
    /// 显示或隐藏画幅比例view
    func setAspectRatioView(shown: Bool) {
        view.bringSubviewToFront(aspectRatioView)
        Wmc_ViewSpringAnimation(aspectRatioView, isShow: shown)
    }
    
    /// 显示或隐藏闪光灯选择view
    private func setFlashSelectView(shown: Bool, mode: YPGECamera.FlashMode? = nil) {
        if let mode = mode {
            flashSelectView.mode = mode
        }
        view.bringSubviewToFront(flashSelectView)
        Wmc_ViewSpringAnimation(flashSelectView, isShow: shown)
    }
    
    /// 跳转分辨率页面
    private func pushResolutionVC() {
        let vm = WmcResolutionVM(aspectRatio: aspectRatioView.aspectRatio)
        vm.resolutionLevel = viewModel.resolutionLevel
        guard let vc = WmcNavigatorManager.push(.resolution, parms: vm) as? WmcResolutionVC else { return }
        vc.didSelectedResolution.subscribe(onNext: {
            [weak self] resolution in
            guard let self = self else { return }
            // 记录选择的分辨率级别
            self.viewModel.resolutionLevel = resolution.level
            // 更新相机的分辨率
            self.setCameraPreset()
            // 存储到本地
            WmcUserdefault.save(value: resolution.level.rawValue, forKey: .State.Camera.resolution)
        }).disposed(by: self.rx.disposeBag)
    }
    
    /// 隐藏/显示滤镜View
    func setFilterView(shown: Bool) {
        filterView.setHidden(!shown)
    }
    
    /// 添加滤镜
    func addFilter() {
        cameraView?.removeAllFilter()
        guard let filter = viewModel.selectedFilterItem?.filter else { return }
        cameraView?.appendFilter(filter)
    }
    
    
    /// 切换视频清晰度后调用
    func didSwitched(articulation: YPGEVideoBuffer.Articulation) {
        YPDevice.PlayShake(.heavy)
        cameraView?.setWriterArticulation(articulation)
        switch articulation {
        case ._1080p:
            let alert = WmcAlertView()
            alert.title = "1080P同步时，会特别耗时及耗费流量"
            alert.msg = "同步视频，建议切换回720P或540P模式"
            alert.style = .confirm(title: "我知道了")
            alert.show()
        default: break
        }
        WmcDebug("保存视频清晰度=====>\(articulation.rawValue)")
        WmcUserdefault.save(value: articulation.rawValue, forKey: .State.Camera.videoArticulation)
    }
    
    
    // MARK: Private
    
    
  
    

}
